//附件公共方法
import { UploadOutlined , CloudUploadOutlined} from '@ant-design/icons';
import { ReactSortable } from "react-sortablejs";
import myMessage from "../../utils/message"
import React, { useEffect, useRef, useState } from "react";
import clsx from 'clsx';
import { Checkbox, Modal, Upload, Button, Tooltip, message, Spin} from "antd";
import { useFormField } from "../../context/form-context";
import { useForm } from "../../context/metadata-context";
import cloneDeep from "lodash/cloneDeep";
import _extend from "lodash/extend";
import moment from "moment";
import "./index.css";
import { useSelections, useUpdate } from "ahooks";
import request from "../../utils/request";
import { openWin, isIE, buildUrl, formatNumber, fileIsUploading } from "../../utils";
import ntkoBrowser from "../../../../ntko/ntkobackground.min.js"
import { useInject } from '../../context/inject-context';
import eventBus, { useSubscribe } from '../../eventBus';

//设置附件排序
function setFile_sort ({
  params,
  cell,
  fileListCurrent
}){
let value = [];

    //file_sort这个数据，可以优化为不给后端，但是需要后端配合
    let file_sort = params.file_sort || {};//排序信息
    file_sort[cell.code] = [];//清空file_sort，下面再循环追加最新排序
    
    Object.keys(fileListCurrent.__fileType__).forEach(function(typeKey){
      let typeInfo = fileListCurrent.__fileType__[typeKey];//分类信息
      typeInfo.data.forEach(function(file, index){
        value.push(file.id);//追加id信息
        file_sort[cell.code].push({
          ...file,
          ...{
            order_code: value.length//重写排序，后端需要这个进行排序
          }
        });

      });
    })

    params.file_sort = file_sort;//重写排序信息
    value = value.join(",");//当前字段生成字符串value
    return value;
}

//更新附件
//fileId要更新的附件id typeKey附件所在附件分类key updateInfo要更新的数据
function updateFile({
  updater,
  fileListCurrent,
  fileId, 
  typeKey, 
  updateInfo
}){
  let fileList = fileListCurrent.__fileType__?.[typeKey];
  let returnData = null;
  if(fileList?.data?.length){
    fileList.data.find(function(item, index){
      if(item.id === fileId){//找到对应分类下，需要删除的文件
        item = {
          ...item,
          ...updateInfo
        }//把新的数据覆盖到原有的附件
        fileList.data[index] = item;
        returnData = item;
        return true;
      }
    });
  }
  updater();//只更新列表数据，不更新tpldata
  return returnData;//返回当前更新后的附件
}

//根据附件id查找分类
function _getFileType({
  fileId,
  fileListCurrent
}){
  let typeKey;
  Object.keys(fileListCurrent.__fileType__).find(function(fileTypeKey){//1.遍历所有分类
    let fileInfo = fileListCurrent.__fileType__[fileTypeKey];
    if(fileInfo?.data){
      let allFileIds = fileInfo.data.map(function(file){
        return file.id;
      });//拿到当前分类下所有附件id
      if(allFileIds.indexOf(fileId) > -1){
        typeKey = fileTypeKey;//当前分类存在这个附件，返回这分类信息
        return true;
      }
    }
  })
  return typeKey;
}

//把签出的文件变为未签出
function resetFileState ({
  fileId, 
  typeKey,
  fileListCurrent,
  updater
}) {
  if(!fileId){
    console.log("签入附件缺失了附件id");
    return;
  }
  if(!typeKey){//如果没有传附件类型
    typeKey = _getFileType({
      fileListCurrent: fileListCurrent,
      fileId: fileId
    });//找到对应的分类
  }
  updateFile({
    fileListCurrent: fileListCurrent,
    updater: updater,
    fileId: fileId,
    typeKey: typeKey,
    updateInfo: {
      is_edit : false, //编辑
      is_checkin : false, //签入
      LockedUser: null, //签出信息
      is_checkout_and_edit : true,//签出并编辑
      is_delete: true//删除
    }
  });
  updater();//只更新列表数据，不更新tpldata
}

//签入
function checkInFile({
  file, 
  typeKey, 
  mytype,
  updater,
  params,
  form,
  fileListCurrent
}){
  if(mytype === "checkin"){//直接签入 这种情况是ntko编辑页面直接触发的签入
      resetFileState({
        updater: updater,
        fileId: file.id, 
        typeKey: typeKey,
        fileListCurrent: fileListCurrent
      });
      return;
  }
  file.__fileLoading__ = true;//文件loading状态
  updater();//只更新列表数据，不更新tpldata
  //调用请求进行实际签入
  request({
      url: "/attachment/ajax-checkin?"+"t="+Math.random(),
      method: "POST",
      isForm: true,
      data:`doc_guid=${file.id}&package_id=${params.package_id || ''}`
  }).then(function(ref){
    file.__fileLoading__ = false;
    if(ref.code===1){//签入成功
      form.forceUpdate = {};
      resetFileState({
        updater: updater,
        fileId: file.id, 
        typeKey: typeKey,
        fileListCurrent: fileListCurrent
      });
    }
    updater();//只更新列表数据，不更新tpldata
  },function(){
    file.__fileLoading__ = false;
    updater();//只更新列表数据，不更新tpldata
  });
}

//获取附件图标
function getFileIcon(filename) {
  var fileExtIconDic = {
    pdf: "icon-pdf",
    txt: "icon-txt",
    ppt: "icon-ppt",
    pptx: "icon-ppt",
    doc: "icon-word",
    docx: "icon-word",
    xls: "icon-excel",
    xlsx: "icon-excel",
    rar: "icon-rar",
    zip: "icon-rar",
    "7z": "icon-rar",
    jpg: "icon-img",
    jpeg: "icon-img",
    png: "icon-img",
    gif: "icon-img",
    bmp: "icon-img",
    ico: "icon-img",
    avi: "icon-icon-video",
    mpg: "icon-icon-video",
    mpeg: "icon-icon-video",
    mov: "icon-icon-video",
    wav: "icon-icon-video",
    ram: "icon-icon-video",
    mp3: "icon-icon-video",
    mp4: "icon-icon-video",
    xml: "icon-txtbeifen",
    unkown: "icon-buzhiming",
  };
  var ext = "";
  var arr = filename.split(".");
  if (arr.length < 2) {
    ext = "unkown";
  } else {
    ext = arr[arr.length - 1];
  }
  var icon = fileExtIconDic[ext.toLowerCase()];
  if (typeof icon === "undefined") return fileExtIconDic["unkown"];
  return icon;
}

//附件预览
function filePreview({
  params,
  tplData,
  file
}){
  request({
    url: "/attachment/ajax-get-view-url?"+"t="+Math.random(),
    method: "get",
    data: {
      id: file.id,
      is_download: file.is_download ? 1 : 0,
      is_print: file.is_print ? 1 : 0,
      proc_id: tplData.ProcessInfo.ProcessGuid,
      enable_qr_code: tplData.ProcessInfo.EnableQrCode ? 1 : 0,
      is_draft: tplData.ProcessInfo.ProcessStatus == -3 ? 1 : 0,
      package_id: params.package_id || ''
    },
  }).then(function (ref) {
    if(ref.code===1 && ref.data && (typeof ref.data) == "string"){
        //获取预览链接末位的文件类型
        var docType = ref.data.split(".");
        docType = docType[docType.length-1];
        docType = docType.toLocaleLowerCase();
        var officesType = ["doc", "docx", "xlsx", "xls", "ppt", "pptx"];//office类型
        if(officesType.indexOf(docType) >-1 && ref.data.indexOf("attachment/view") >-1 && ref.data.indexOf(window.location.origin) == 0){//如果是office类文档，用ntko插件打开
            var ntkoed = ntkoBrowser.ExtensionInstalled();
            if (ntkoed) {//如果已经安装了NTKOPlus，则用ntko的打开方式打开附件
                ntkoBrowser.openWindow(ref.data);
            } else {
                if(isIE()){//如果是IE浏览器，直接window.open
                    window.open(ref.data);
                    return;
                }
                //其他浏览器下载NTKO
                var iTop = ntkoBrowser.NtkoiTop();   //获得窗口的垂直位置;
                var iLeft = ntkoBrowser.NtkoiLeft();        //获得窗口的水平位置;
                window.open("/ntko/exeindex.html?", "", "height=200px,width=500px,top=" + iTop + "px,left=" + iLeft + "px,titlebar=no,toolbar=no,menubar=no,scrollbars=auto,resizeable=no,location=no,status=no");
            }
        }else{
            openWin(ref.data);
        }
    }
  }).catch(function (result) {
    //callback(""); 原有的预览失败啥都没做
  });
}

//获取附件是否可编辑
function canFileEdit({
  tplData,
  file
}) {
  if (tplData.fileEditButton === false) {
    //true 可编辑 false 不可编辑，只有文档服务2.0才支持编辑
    return false;
  }
  if (!file.name) {
    return false;
  }
  file.FileExtension = file.name.split(".")[file.name.split(".").length - 1];
  var fileType = file.FileExtension.toLowerCase();
  if (fileType == "doc" || fileType == "docx" || fileType == "xls" || fileType == "xlsx") {
    return true;
  }
  return false;
}

//判断是否Safari浏览器
function isSafari(){
  let safari = false;
  var userAgent = navigator.userAgent.toLowerCase(); //取得浏览器的userAgent字符串
  if (userAgent.indexOf("safari") > -1 && userAgent.indexOf("chrome") < 0) {
    //如果浏览器标识包含Safari并且不包含chrome，则是safari浏览器
    safari = true;
  } 
  return safari;
}

//编辑
function fileEdit({
  file,
  tplData,
  urlPrefix
}) {
  var url = "/flowinstance/approval/ntko";
  if (urlPrefix) {
      url = urlPrefix + url;
  }

  var urlParam = {
      _mode: 2,
      _oid: file.id,
      _docName: file.name.trim(),
      _canDocModify: file.is_edit? 1 : 0,//修改
      _canDocFinalize: file.is_finalize? 1 : 0,//修订
      _stepGuid: '',//tplData.StepDefaultInfo.StepGuid,
      _nodeGuid: tplData.NodeInfo.node_id,
      _UserCode: tplData.CurUserCode,//tplData.CurUserCode
      _UserName: tplData.CurUserName,
      _fileId: file.id,
      _packageId: tplData.package_id
  };

  if (urlPrefix) {
      urlParam._urlprefix = encodeURIComponent(urlPrefix);//多租户模式
  }

  file.FileExtension = file.name.split(".")[file.name.split(".").length - 1];
  var fileType = file.FileExtension.toLowerCase();

  if (fileType == "doc" || fileType == "docx") {
      urlParam._docType = 1;
  } else if (fileType == "xls" || fileType == "xlsx") {
      urlParam._docType = 3;
  }
  if (urlParam._docType) {
      var ntkoed = ntkoBrowser.ExtensionInstalled();
      url = buildUrl(url, urlParam);
      if (ntkoed) {//如果已经安装了NTKOPlus，则用ntko的打开方式打开附件
        //ntkoBrowser.openWindow("http://10.5.10.167:9080" + url);//用来测试直接open
        ntkoBrowser.openWindow(url);
      } else {
          if(isIE()){//如果是IE浏览器，直接window.open
              window.open(url);
              return;
          }
          //其他浏览器下载NTKO
          var iTop = ntkoBrowser.NtkoiTop();   //获得窗口的垂直位置;
          var iLeft = ntkoBrowser.NtkoiLeft();        //获得窗口的水平位置;
          window.open("/ntko/exeindex.html?", "", "height=200px,width=500px,top=" + iTop + "px,left=" + iLeft + "px,titlebar=no,toolbar=no,menubar=no,scrollbars=auto,resizeable=no,location=no,status=no");
      }
  } else {
    message.info({
      content: "不支持" + file.FileExtension + "格式"
    })
  }
}

//签出并编辑 签出&编辑 签出编辑
function checkoutAndEdit({
  file, 
  typeKey,
  updater,
  params,
  form,
  fileListCurrent,
  tplData,
  urlPrefix
}){
  let fileId = file.id;
  file.__fileLoading__ = true;//文件loading状态
  updater();//只更新列表数据，不更新tpldata
  request({
      url: "/attachment/ajax-checkout?"+"t="+Math.random(),
      method: "POST",
      isForm: true,
      data:`doc_guid=${file.id}&package_id=${params.package_id || ''}`,
  }).then(function(ref){
    file.__fileLoading__ = false;
    
    if(ref.code===1){//签出成功
      form.forceUpdate = {};
      let _updateFile = updateFile({
        updater:updater,
        fileListCurrent: fileListCurrent,
        fileId: fileId,
        typeKey: typeKey,
        updateInfo: {
          is_edit : true, //编辑
          is_checkin : true, //签入
          LockedUser: "【" + tplData.CurUserName +"】签出", //签出信息
          is_checkout_and_edit : false,//签出并编辑
          is_delete: false//删除
        }
      });
      if(_updateFile){
        fileEdit({
          file: _updateFile,
          tplData: tplData,
          urlPrefix: urlPrefix
        });
      }
    }
    updater();//只更新列表数据，不更新tpldata
  }, function(){
    file.__fileLoading__ = false;
    updater();//只更新列表数据，不更新tpldata
  })
}

//附件下载
function fileDownload({
  id,
  params,
  tplData,
  urlPrefix
}) {
  if (id.length > 1) {
    //批量下载
    request({
      url: "/attachment/save-files-id", //根据url获取带token的超链接
      method: "post",
      isForm: true,
      data:`ids=${JSON.stringify(id)}&package_id=${params.package_id || ''}`
    }).then(
      function (result) {
        if (result.code == 1 && result.data) {
          //后端返回result.data，根据result.data下载多个附件
          var url = "/attachment/ajax-downloads?fileid=" + result.data + "&package_id=" + params.package_id || "";
          _downFile({
            url: url,
            tplData: tplData,
            urlPrefix: urlPrefix
          });
        }
      },
      function(result){
        myMessage.info({
          content: result?.message || "下载失败"
        });
      }
    );
    return;
  }
  //ids 通过post传值
  var ids = JSON.stringify(id);
  var url = "/attachment/ajax-downloads?ids=" + ids + "&package_id=" + params.package_id || "";
  _downFile({
    url: url,
    tplData: tplData,
    urlPrefix: urlPrefix
  });
}
function _downFile({
  url,
  tplData,
  urlPrefix
}) {
  var mainTitle = tplData.ProcessInfo.Title;
  if (mainTitle && mainTitle != "") {
    url = url + "&name=" + encodeURIComponent(mainTitle);
  }
  if (tplData.ProcessInfo.ProcessGuid) {
    url = url + "&proc_id=" + tplData.ProcessInfo.ProcessGuid;
  }
  if (tplData.ProcessInfo.ProcessStatus == -3) {
    url = url + "&is_draft=1";
  }
  if (urlPrefix) {
      url = urlPrefix + url;
  }
  openWin(url + "&t=" + Math.random());
}

//记录删除的附件id
function setDelete_attachments({
  fileId,
  params
}){
  if(!fileId){
    return;
  }
  //记录删除的附件id
  if(!params.delete_attachments){
    params.delete_attachments = [];
  }
  params.delete_attachments.push(fileId);
}

//附件删除 删除附件 - 带确认框的删除
function deleteFile({
  fileId, 
  typeKey, 
  showConfirm = false,
  params,
  cell,
  fileListCurrent,
  fileIdList,
  fieldConfig,
  updater
}){
  if(!showConfirm){//不需要确认框，直接移除
    setDelete_attachments({
      fileId: fileId,
      params: params
    });//记录删除的附件key
    _removeFiled({
      fileId: fileId,
      typeKey: typeKey,
      fileListCurrent: fileListCurrent
    });//移除记录
    return;
  }

  //有附件正在上传中，不让删除
  //验证是否有上传中的附件
  let fileUploadingRes = fileIsUploading({
    tipMessage: "文件正在上传，请稍后删除。" 
  })
  if(fileUploadingRes){
      return false;//存在上传中的附件不做后续校验
  }

  myMessage.confirmSM({
    content: "确认删除此附件？",
    onOk:function(){
      _removeFiled({
        fileId: fileId,
        typeKey: typeKey,
        fileListCurrent: fileListCurrent
      });//移除记录

      setDelete_attachments({
        fileId: fileId,
        params: params
      });//记录删除的附件key

      message.success('删除成功');
      setValue({
        params: params,
        cell: cell,
        fileListCurrent: fileListCurrent,
        fileIdList: fileIdList,
        fieldConfig: fieldConfig,
        updater: updater
      });//更新字段信息
    }
  });
}
//移除附件 - 从变量删除
//fileId要删除的附件id typeKey附件所在附件分类key
function _removeFiled({
  fileId, 
  typeKey,
  fileListCurrent
}){
  let fileList = fileListCurrent.__fileType__?.[typeKey];
  if(fileList?.data?.length){
    fileList.data.forEach(function(item, delIdx){
      if(item.id === fileId){//找到对应分类下，需要删除的文件
        fileList.data.splice(delIdx,1);//删除
      }
    });
  }
}

//设置字段的值
function setValue({
  params,
  cell,
  fileListCurrent,
  fileIdList,
  fieldConfig,
  updater
}){
  let value = setFile_sort({
    params: params,
    cell: cell,
    fileListCurrent: fileListCurrent
  });//设置附件排序，并获得当前字段最新的附件id字符串
  fileIdList.current = value.split(",");//更新全选/反选附件id
  fieldConfig.onChange(value);//触发字段change事件，改变tplData

  updater();//只更新列表数据，不更新tpldata
}

export {
  setFile_sort,//设置附件排序
  checkInFile, //签入附件
  updateFile,//更新附件
  getFileIcon,//返回附件图标
  filePreview,//附件预览
  canFileEdit,//获取附件是否可编辑
  isSafari,//是否safari浏览器
  fileEdit,//附件编辑
  checkoutAndEdit,//附件签出&编辑
  fileDownload,//附件下载
  deleteFile,//附件删除 删除附件 - 带确认框的删除
  setValue,//更新字段值
  setDelete_attachments,//更新params删除附件id
}